package com.bj58.groupbuy.action.controllers;

import java.util.ArrayList;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.ServletRequestUtils;

import com.alibaba.fastjson.JSONObject;
import com.bj58.groupbuy.action.charts.ViewResult;
import com.bj58.groupbuy.action.interceptors.Check;
import com.bj58.groupbuy.action.model.IndexManager;
import com.bj58.groupbuy.action.model.ReportManager;
import com.bj58.groupbuy.action.service.IndexManagerService;
import com.bj58.groupbuy.action.util.DateUtil;
import com.bj58.groupbuy.action.util.SomePublicUtil;
import com.bj58.groupbuy.service.locator.ServiceLocator;
import com.bj58.groupbuy.wf.page.Paginate;
import com.bj58.wf.mvc.ActionResult;
import com.bj58.wf.mvc.BeatContext.Model;
import com.bj58.wf.mvc.actionresult.ContentResult;
import com.bj58.wf.mvc.MvcController;
import com.bj58.wf.mvc.annotation.GET;
import com.bj58.wf.mvc.annotation.POST;
import com.bj58.wf.mvc.annotation.Path;

/**  指标管理
 * @author wangchonglu  2016年3月2日 
 *
 */
@Path("indexManager")
public class IndexManagerController extends MvcController{
	private final IndexManagerService indexManagerService = ServiceLocator.get(IndexManagerService.class);
	private final SomePublicUtil spu = new SomePublicUtil();
	/**
	 *  查询
	 * @return
	 */
	@Path("search")
	@Check("indexManager/search")
	@POST
	@GET
	public ActionResult search() {
		HttpServletRequest request = beat.getRequest();
		Model model =beat.getModel();
		try{
			String indexInfo = ServletRequestUtils.getStringParameter(request, "indexInfo", "");
			String indexName = ServletRequestUtils.getStringParameter(request, "indexName", "");
			
			//设置指标类型
			List<String> indexTypeList = indexManagerService.getIndexType("indexType");
			//一级类别
			List<String> cate1List = indexManagerService.getIndexType("cate1");
			//二级类别
			List<String> cate2List = indexManagerService.getIndexType("cate2");
			
			model.add("indexTypeList",indexTypeList);
			model.add("cate1List",cate1List);
			model.add("cate2List",cate2List);
			model.add("indexInfo1",indexInfo);
			model.add("indexName1",indexName);
			
			//获取页码
			int pageindex = ServletRequestUtils.getIntParameter(request,"pageindex",1);
			int beginpagenum=(pageindex-1)*20;
			
			StringBuffer url = new StringBuffer(); //分页查询参数	
			url.append("&indexInfo="+indexInfo);
			url.append("&indexName="+indexName);		
			
			//分页查询
			Map<String,String> map = new HashMap<String,String>();
			map.put("table", "ir_index");
			int count = 0;
			if("".equals(indexInfo) && "".equals(indexName)){
				count = indexManagerService.getTotalCountByTable(map);
			}else{	
				map.put("indexInfo",indexInfo);
				map.put("indexName",indexName);
				count = indexManagerService.getTotalCountByTable(map);
			}
			
			List<IndexManager>resultlist = new ArrayList<IndexManager>();
			String condition = " LIMIT "+beginpagenum+","+20+"";			
		    resultlist=indexManagerService.getIndexManagerDataForSql(indexInfo, indexName, condition);		
					
			Paginate<String> pList = new Paginate<String>(count,pageindex,20,null);      
			model.add("pList",pList);      
	        model.add("rsList", resultlist);
	        model.add("paramurl",url.toString());
	        model.add("pageindex",pageindex);
		
		}catch(Exception e){
			e.printStackTrace();
			return new ContentResult("error");
		}
		return ActionResult.view("indexManager/indexManager");
		
	}
	
	/**
	 *   修改和使记录失效
	 */
    @Path("modify/{option}")	
    @POST
    @GET
    public ActionResult modify(String option){
    	HttpServletRequest request = beat.getRequest();	
    	//Model model = beat.getModel();
		try{
			
			String indexName = ServletRequestUtils.getStringParameter(request, "indexName", "");
			
			Map<String,String> map = new HashMap<String,String>();
			//修改信息
			if("update".equals(option)){
				String cate1 = ServletRequestUtils.getStringParameter(request, "cate1", "");
				String cate2 = ServletRequestUtils.getStringParameter(request, "cate2", "");
				String indexType = ServletRequestUtils.getStringParameter(request, "indexType", "");
				String countRule = ServletRequestUtils.getStringParameter(request, "countRule", "");
				String remark = ServletRequestUtils.getStringParameter(request, "remark", "");
				String updatetime = DateUtil.getStringDate(new Date(), "yyyy-MM-dd HH:mm:ss");
				String creater = spu.getUserByCookie(request).getUsername();
				map.put("cate1", cate1);
				map.put("cate2", cate2);
				map.put("indexType", indexType);
				map.put("countRule", countRule);
				map.put("remark", remark);
				map.put("updatetime", updatetime);
				map.put("creater", creater);
			    indexManagerService.updateData(indexName, map);
			}else{
				//删除信息
				String state = "0";
				map.put("indexName", indexName);
				map.put("state", state);
				indexManagerService.updateData(indexName, map);
			}		
		   
		}catch(Exception e){
			e.printStackTrace();
			return new ContentResult("error");
		}
		return new ContentResult("success");
    	
    }
    
    /**
	 *   修改和使记录失效
	 */
    @Path("add")	
    @POST
    @GET
    public ActionResult add(){
    	HttpServletRequest request = beat.getRequest();
		
		try{
			String indexName = ServletRequestUtils.getStringParameter(request, "indexName", "");
			String indexInfo = ServletRequestUtils.getStringParameter(request, "indexInfo", "");
			String cate1 = ServletRequestUtils.getStringParameter(request, "cate1", "");
			String cate2 = ServletRequestUtils.getStringParameter(request, "cate2", "");
			String indexType = ServletRequestUtils.getStringParameter(request, "indexType", "");
			String countRule = ServletRequestUtils.getStringParameter(request, "countRule", "");
			String remark = ServletRequestUtils.getStringParameter(request, "remark", "");
			boolean isExist = indexManagerService.isIndexNameExist(indexName);    //true为存在
			if(isExist){
				return new ContentResult("exist");
			}
			String creater = spu.getUserByCookie(request).getUsername();
			int r = indexManagerService.insert(indexName,indexInfo,cate1,cate2,indexType,countRule,remark,creater);
			if(r==0){
				return new ContentResult("error");
			}else{
				return new ContentResult("success");
			}
		
		}catch(Exception e){
			e.printStackTrace();
			return new ContentResult("error");
		}
		
    	
    }
    
    /**
	 *   提示管理
	 *   @author hzx
	 */
    @Path("tipsManager")	
    @POST
    @GET
    public ActionResult tipsManager(){
    	HttpServletRequest request = beat.getRequest();
		
		try{
			String indexid = ServletRequestUtils.getStringParameter(request, "indexid", "");
			IndexManager indexlistresult = indexManagerService.getIndexDataByid(indexid);    //true为存在
			if(indexlistresult!=null)
			{
				JSONObject infojson=new JSONObject();
				infojson.put("infoRule", indexlistresult.getCountRule());
				infojson.put("infoRemark", indexlistresult.getRemark());
				return ViewResult.jsonView(infojson.toJSONString());
			}else {
				return new ContentResult("error");
			}
			
		
		}catch(Exception e){
			e.printStackTrace();
			return new ContentResult("error");
		}
		
    	
    }
    
    /**
	 * 指标查询
	 * 
	 * @return
	 */
	@Path("indexQuery")
	@POST
	@GET
	public ActionResult indexQuery() {
		HttpServletRequest request = beat.getRequest();
		Model model =beat.getModel();
		try{
			String cate1 = ServletRequestUtils.getStringParameter(request, "cate1", "");
			String catetype = ServletRequestUtils.getStringParameter(request, "catetype", "");
			List<ReportManager> cate1List = indexManagerService.getReportCate1();//确定所有一级类
	     	model.add("cate1List",cate1List);
			if("1".equals(catetype))
			{
				 JSONObject infojson=new JSONObject();
				 List<ReportManager> cate2List = indexManagerService.getReportCate2ByCate1(cate1);//根据第一个一级类，加载该类下所有二级类
				 infojson.put("cate2List", cate2List);
				 return ViewResult.jsonView(infojson.toJSONString());
			}else if("2".equals(catetype)){
				 String cate2 = ServletRequestUtils.getStringParameter(request, "cate2", "");
				 JSONObject infojson=new JSONObject();
				 List<ReportManager> indexTypelist = indexManagerService.getReportIndexByCate2(cate1,cate2);
				 infojson.put("indexTypelist", indexTypelist);
				 return ViewResult.jsonView(infojson.toJSONString());	
			}else if("3".equals(catetype)){
				 String cate2 = ServletRequestUtils.getStringParameter(request, "cate2", "");
				 String indextype = ServletRequestUtils.getStringParameter(request, "indextype", "");
				 JSONObject infojson=new JSONObject();
				 List<ReportManager> indexNameList = indexManagerService.getReportIndexByIndexType(cate1,cate2,indextype);
				 
				 /**获取页码*/
					int pageindex = ServletRequestUtils.getIntParameter(request,"pageindex",1);//页数。
					List<ReportManager> rslist = new ArrayList<ReportManager>();
					for (int i = (pageindex - 1) * 20; i < indexNameList.size()
							&& i < pageindex * 20; i++) {
						rslist.add(indexNameList.get(i));
					}
					int pagecount=indexNameList.size()/20+1;
					infojson.put("count",indexNameList.size());
					infojson.put("CurrentPageNo",pageindex);
					infojson.put("pagecount",pagecount);
					infojson.put("indexNameList", rslist);
				 return ViewResult.jsonView(infojson.toJSONString());	
			}else if("4".equals(catetype)){
				 String Id = ServletRequestUtils.getStringParameter(request, "indexid", "");
			     JSONObject infojson=new JSONObject();
				 List<ReportManager> reportList = indexManagerService.getReportById(Id);
				 if(reportList.size()>0)
				 {
					 IndexManager indexlist=indexManagerService.getIndexDataByid(reportList.get(0).getIndexName());
					 infojson.put("Index",indexlist);
					 infojson.put("Report", reportList);
					 return ViewResult.jsonView(infojson.toJSONString());
				 }
			}else if("5".equals(catetype)){
				 String searchtext = ServletRequestUtils.getStringParameter(request, "searchtext", "");
			     JSONObject infojson=new JSONObject();
				 List<ReportManager> reportList = indexManagerService.getReportByInput(searchtext);
				 
				 /**获取页码*/
					int pageindex = ServletRequestUtils.getIntParameter(request,"pageindex",1);//页数。
					List<ReportManager> rslist = new ArrayList<ReportManager>();
					for (int i = (pageindex - 1) * 20; i < reportList.size()
							&& i < pageindex * 20; i++) {
						rslist.add(reportList.get(i));
					}
					int pagecount=reportList.size()/20+1;
					infojson.put("count",reportList.size());
					infojson.put("CurrentPageNo",pageindex);
					infojson.put("pagecount",pagecount);
					infojson.put("indexNameList", rslist);
				 return ViewResult.jsonView(infojson.toJSONString());
			}
		}catch(Exception e){
			e.printStackTrace();
			return new ContentResult("error");
		}
		return ActionResult.view("indexManager/indexQuery");
	}
    
    /**
     *   报表管理   查询
     */
    @Path("report/search")
    @POST
    @GET
    public ActionResult getReport(){
    	HttpServletRequest request = beat.getRequest();
		Model model =beat.getModel();
		try{
			String indexName = ServletRequestUtils.getStringParameter(request, "indexName", "");
			String tableInfo = ServletRequestUtils.getStringParameter(request, "tableInfo", "");
			
			String condition1 = "";
			List<String> cate1List = indexManagerService.getReportTypeName("cate1",condition1);
			condition1 = "cate1='"+cate1List.get(0)+"'";
			List<String> cate2List = indexManagerService.getReportTypeName("cate2",condition1);
			condition1 = "cate1='"+cate1List.get(0)+"' and cate2='"+cate2List.get(0)+"'";
			List<String> indexNameList = indexManagerService.getReportTypeName("indexName",condition1);
			model.add("indexNameList",indexNameList);
			model.add("cate1List",cate1List);
			model.add("cate2List",cate2List);
			model.add("tableInfo1",tableInfo);
			model.add("indexName1",indexName);
			
			
			//获取页码
			int pageindex = ServletRequestUtils.getIntParameter(request,"pageindex",1);
			int beginpagenum=(pageindex-1)*20;
			
			StringBuffer url = new StringBuffer(); //分页查询参数	
			url.append("&tableInfo="+tableInfo);
			url.append("&indexName="+indexName);		
			
			//分页查询
			Map<String,String> map = new HashMap<String,String>();
			map.put("table", "ir_tableindex");
			
			int count = 0;
			if("".equals(tableInfo) && "".equals(indexName)){
				count = indexManagerService.getTotalCountByTable(map);
			}else{	
				map.put("tableInfo",tableInfo);
				map.put("indexName",indexName);
				count = indexManagerService.getTotalCountByTable(map);
			}
			
			
			List<ReportManager> resultlist = new ArrayList<ReportManager>();
			
			String condition = " LIMIT "+beginpagenum+","+20+"";	
			resultlist=indexManagerService.getReportManagerList(map,condition);					
			Paginate<String> pList = new Paginate<String>(count,pageindex,20,null);      
			model.add("pList",pList);      
	        model.add("rsList", resultlist);
	        model.add("paramurl",url.toString());
	        model.add("pageindex",pageindex);
		
		}catch(Exception e){
			e.printStackTrace();
			return new ContentResult("error");
		}
		return ActionResult.view("indexManager/reportManager");
    	
    }
    

	/**
	 *   修改和使记录失效
	 */
    @Path("report/modify/{option}")	
    @POST
    @GET
    public ActionResult reportModify(String option){
    	HttpServletRequest request = beat.getRequest();	
    	//Model model = beat.getModel();
		try{
			
			Map<String,String> map = new HashMap<String,String>();
			//修改信息
			if("update".equals(option)){
				String tableName = ServletRequestUtils.getStringParameter(request, "tableName", "");
				String id = ServletRequestUtils.getStringParameter(request, "id", "");
				String tableInfo = ServletRequestUtils.getStringParameter(request, "tableInfo", "");
				String remark = ServletRequestUtils.getStringParameter(request, "remark", "");
				
				map.put("tableName", tableName);
				map.put("id", id);
				map.put("tableInfo", tableInfo);
				map.put("remark", remark);
			    int i = indexManagerService.updateReportData("ir_tableindex", map);
			    if(i==1){
			    	return new ContentResult("success");
			    }else{
			    	return new ContentResult("error");
			    }
			    
			}	
		   
		}catch(Exception e){
			e.printStackTrace();
			return new ContentResult("error");
		}
		return new ContentResult("success");
    	
    }
    
    /**
	 *   修改和使记录失效
	 */
    @Path("report/add")	
    @POST
    @GET
    public ActionResult reportAdd(){
    	HttpServletRequest request = beat.getRequest();
		
		try{
			String indexName = ServletRequestUtils.getStringParameter(request, "indexName", "");
			String tableName = ServletRequestUtils.getStringParameter(request, "tableName", "");
			String cate1 = ServletRequestUtils.getStringParameter(request, "cate1", "");
			String cate2 = ServletRequestUtils.getStringParameter(request, "cate2", "");
			String tableInfo = ServletRequestUtils.getStringParameter(request, "tableInfo", "");
			String remark = ServletRequestUtils.getStringParameter(request, "remark", "");
			
			int r = indexManagerService.insertReportData(tableName, indexName, tableInfo, cate1, cate2, remark);
			if(r==0){
				return new ContentResult("error");
			}else{
				return new ContentResult("success");
			}
		
		}catch(Exception e){
			e.printStackTrace();
			return new ContentResult("error");
		}	
    }  
    
    /**
     *  加载类别
     */
    @Path("report/getType/{cate}")
    @POST
    @GET
    public ActionResult getType(String cate){
        HttpServletRequest request = beat.getRequest();	
		try{
			JSONObject json = new JSONObject();
			String condition1 = "";
			String cate1 = ServletRequestUtils.getStringParameter(request, "cate1", "");				
			if("cate1".equals(cate)){		
				List<String> cate2List = indexManagerService.getReportTypeName("cate2","cate1='"+cate1+"'");				
				condition1 = "cate1='"+cate1+"' and cate2='"+cate2List.get(0)+"'";
				List<String> indexNameList = indexManagerService.getReportTypeName("indexName",condition1);
				json.put("cate2List",cate2List);
				json.put("indexNameList",indexNameList);
				return ViewResult.jsonView(json.toString());
			}
			String cate2 = ServletRequestUtils.getStringParameter(request, "cate2", "");
			List<String> indexNameList = indexManagerService.getReportTypeName("indexName","cate2='"+cate2+"'");
			json.put("indexNameList",indexNameList);
			return ViewResult.jsonView(json.toString());
		}catch(Exception e){
			e.printStackTrace();
			return new ContentResult("error");
		}	
		
    	
    }
  /*  @Path("/iframe_res")
    @POST
	@GET
    public ActionResult iframeResult() {
    	HttpServletRequest request = beat.getRequest();
		Model model =beat.getModel();
		try{
			String cate1 = ServletRequestUtils.getStringParameter(request, "cate1", "");
			List<ReportManager> cate1List = indexManagerService.getReportCate1();//确定所有一级类
	     	model.add("cate1List",cate1List);
	     	String cate2 = ServletRequestUtils.getStringParameter(request, "cate2", "");
			String indextype = ServletRequestUtils.getStringParameter(request, "indextype", "");
			List<ReportManager> indexNameList = indexManagerService.getReportIndexByIndexType(cate1,cate2,indextype);
			String catetype = ServletRequestUtils.getStringParameter(request, "catetype", ""); 
			*//**获取页码*//*
			int pageindex = ServletRequestUtils.getIntParameter(request,"pageindex",1);//页数。
			StringBuffer url =new StringBuffer();//分页的URL
		    url.append("&cate2="+cate2);
		    url.append("&indextype="+indextype);
		    url.append("&cate1="+cate1);
		    url.append("&catetype=3");
		    
		    Paginate<String> pList = new Paginate<String>(
		    		indexNameList.size(), pageindex, 12, null);
			model.add("pList", pList);
			model.add("paramurl", url.toString());
			model.add("pageindex",pageindex);
    	
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return ActionResult.view("indexManager/iframe_res");
	}*/
}

